from datetime import timedelta

from odoo import api, fields, models
from odoo.exceptions import UserError

PLAN_CATEGORY = [('birth', '生日'), ('register', '注册'), ('holiday', '节日'), ('activity', '活动')]
PLAN_STATUS = [('await', '待生效'), ('drift', '草稿'), ('create', '创建'), ('discard', '弃用')]


class RpMarketingCouponTaskPlan(models.Model):
    _name = 'rp.marketing.coupon.task.plan'
    _description = '优惠券计划'

    # 基础
    name = fields.Char(string='名称', copy=False)
    code = fields.Char(string='编码', default='RP_MCT/', copy=False)
    type = fields.Selection(string='类型', selection=PLAN_CATEGORY, required=True, copy=False)
    rp_festival_id = fields.Many2one(string='节日', comodel_name='rp.festival', domain=[('actual_begin_date', '>=', fields.date.today())], copy=False)  # 只筛出开始时间位于今天及之后的
    actual_begin_date = fields.Date(string='实际开始时间', copy=False, compute='compute_on_type')
    actual_end_date = fields.Date(string='实际结束时间', copy=False, compute='compute_on_type')

    # 域信息
    rp_customer_special_tag = fields.Boolean(string='特殊客户标志', copy=False)
    customer_category_tag = fields.Boolean(string='分类', default=False)
    rp_customer_category_ids = fields.Many2many(string='客户分类', comodel_name='rp.customer.category', column1='rp_marketing_coupon_task_plan_id', column2='rp_customer_category_id',
                                                relation='rp_marketing_coupon_task_plan_customer_category_rel', compute='compute_category_tag', copy=False, store=True)
    customer_level_tag = fields.Boolean(string='等级', default=False)
    rp_customer_level_ids = fields.Many2many(string='客户等级', comodel_name='rp.customer.level', column1='rp_marketing_coupon_task_id', column2='rp_customer_level_id',
                                             relation='rp_marketing_coupon_task_plan_customer_level_rel', compute='compute_level_tag', copy=False, store=True)
    customer_tag = fields.Boolean(string='客户', default=False)
    rp_customer_ids = fields.Many2many(string='客户', comodel_name='rp.customer', copy=False)

    plan_coupon_ids = fields.One2many(string='优惠券', comodel_name='rp.marketing.coupon.task.plan.line', inverse_name='task_plan_id', copy=False)
    plan_status = fields.Selection(string='状态', selection=PLAN_STATUS, default=PLAN_STATUS[1][0], copy=False)
    enable_statue = fields.Boolean(string='激活', default=False, copy=False)

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['code'] = self.env['ir.sequence'].next_by_code('rp.marketing.coupon.task.plan') or '/'
        result_list = super(RpMarketingCouponTaskPlan, self).create(vals_list)
        # 更新状态
        response_list = []
        for result in result_list:
            if result.actual_begin_date <= fields.date.today() <= result.actual_end_date:
                result.write({'plan_status': 'create'})
            if result.actual_begin_date > fields.date.today():
                result.write({'plan_status': 'await'})
            response_list.append(result)
        return result_list

    @api.constrains('plan_coupon_ids')
    def constraint_on_value(self):
        for record in self:
            # 优惠券判断
            if record.plan_coupon_ids:
                no_repeat_records = set(record.plan_coupon_ids.mapped(lambda r: r.rp_marketing_coupon_template_id.id))
                if len(no_repeat_records) < len(record.plan_coupon_ids):
                    raise UserError('优惠券中优惠券模板相同的记录只能有一条！')

    """
    Onchange
    """

    @api.onchange('rp_customer_special_tag')
    def onchange_special_customer_tag(self):
        if self.rp_customer_special_tag:
            self.update({'rp_customer_category_ids': False, 'rp_customer_level_ids': False, 'rp_customer_ids': False,
                         'customer_level_tag': False, 'customer_category_tag': False, 'customer_tag': False})

    @api.onchange('type')
    def onchange_type(self):
        if self.type in ['birth', 'register']:
            self.update({'rp_festival_id': False, 'actual_begin_date': False, 'actual_end_date': False})

    @api.onchange('customer_level_tag', 'customer_category_tag')
    def onchange_category_level_tag(self):
        if self.customer_level_tag:
            self.update({'rp_customer_level_ids': False})
        if self.customer_category_tag:
            self.update({'rp_customer_category_ids': False})

    @api.onchange('rp_customer_level_ids', 'rp_customer_category_ids')
    def onchange_category_level_ids(self):
        domain_list = []
        if len(self.rp_customer_level_ids) > 0:
            domain_list.append(('customer_level', 'in', self.rp_customer_level_ids.ids))
        if len(self.rp_customer_category_ids) > 0:
            domain_list.append(('rp_customer_category', 'in', self.rp_customer_category_ids.ids))
        return {'domain': {'rp_customer_ids': domain_list}}

    """
    Depends
    """

    @api.depends('customer_category_tag')
    def compute_category_tag(self):
        for record in self:
            if record.rp_customer_special_tag:
                record.rp_customer_category_ids = False
            else:
                if record.customer_category_tag:
                    record.rp_customer_category_ids = [(6, 0, record.rp_customer_category_ids.ids)]
                else:
                    rp_customer_category_ids = record.env['rp.customer.category'].search([])
                    record.rp_customer_category_ids = [(6, 0, rp_customer_category_ids.ids)]

    @api.depends('customer_level_tag')
    def compute_level_tag(self):
        for record in self:
            if record.rp_customer_special_tag:
                record.rp_customer_level_ids = False
            else:
                if record.customer_level_tag:
                    record.rp_customer_level_ids = [(6, 0, record.rp_customer_level_ids.ids)]
                else:
                    rp_customer_level_ids = record.env['rp.customer.level'].search([])
                    record.rp_customer_level_ids = [(6, 0, rp_customer_level_ids.ids)]

    @api.depends('type')
    def compute_on_type(self):
        for record in self:
            if record.type == 'holiday' and record.rp_festival_id:
                record.write({'actual_begin_date': record.rp_festival_id.actual_begin_date, 'actual_end_date': record.rp_festival_id.actual_end_date})
            else:
                # 其余情况后续加
                record.write({'actual_begin_date': False, 'actual_end_date': False})

    """
    Button Function
    """

    def fill_task_plan_to_publish(self):
        records = self.browse(self.env.context.get('active_ids'))
        if len(records) > 1:
            raise UserError('配置出错！')
        records[0].write({'coupon_task_plan_id': records[0].id})


class RpMarketingCouponTaskPlanLine(models.Model):
    _name = 'rp.marketing.coupon.task.plan.line'
    _description = '优惠券明细'

    task_plan_id = fields.Char(string='关联主表', copy=False)
    display_name = fields.Char(string='名称', compute='depend_on_template_amount', copy=False, index=True)
    rp_marketing_coupon_template_id = fields.Many2one(string='优惠券模板', comodel_name='rp.marketing.coupon.template', copy=False)
    amount = fields.Integer(string='数量', copy=False, index=True)

    @api.depends('rp_marketing_coupon_template_id', 'amount')
    def depend_on_template_amount(self):
        for record in self:
            if all([record.rp_marketing_coupon_template_id.id, record.amount]):
                record.update({'display_name': f'{record.rp_marketing_coupon_template_id.name}({record.amount})'})
            else:
                record.update({'display_name': 'NEW'})
